from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect, reverse

from web import models
from utils.encrypt import uid
from utils.baidu.bos import upload_file
from web.forms.wiki import WikiModelForm
from django.core.files.uploadedfile import InMemoryUploadedFile
from _io import BytesIO


def wiki(request, project_id):
    """ wiki首页 """
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')
    wiki_obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'wiki.html', {'wiki_obj': wiki_obj})


def wiki_add(request, project_id):
    """ wiki添加 """
    if request.method == 'POST':
        form = WikiModelForm(request, data=request.POST)
        if form.is_valid():
            # 判断用户是否已经选择父文章
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            form.instance.project = request.tracer.project
            form.save()
            return redirect(reverse('web:wiki', kwargs={'project_id': project_id}))
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request)
    return render(request, 'wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    """ wiki目录 """
    # 获取当前项目所有的目录：data = Queryset类型
    data = models.Wiki.objects.filter(project=request.tracer.project).values('id', 'title', 'parent_id').\
        order_by('depth', 'id')
    # JsonResponse在内部会调用json.dumps，而queryset是不能不序列化的 我们简单的做法就是将queryset转化成list
    return JsonResponse({'status': True, 'data': list(data)})


def wiki_delete(request, project_id, wiki_id):
    """ 删除文章 """
    models.Wiki.objects.filter(project=request.tracer.project.id, id=wiki_id).delete()
    return redirect(reverse('web:wiki', kwargs={'project_id': project_id}))


def wiki_edit(request, project_id, wiki_id):
    """ 编辑文章 """
    wiki_obj = models.Wiki.objects.filter(project=request.tracer.project, id=wiki_id).first()
    if not wiki_obj:
        return redirect(reverse('web:wiki', kwargs={'project_id': project_id}))
    if request.method == 'POST':
        form = WikiModelForm(request, instance=wiki_obj, data=request.POST)
        if form.is_valid():
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            form.save()
            return redirect(reverse('web:wiki', kwargs={'project_id': project_id}) + '?wiki_id={}'.format(wiki_id))
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, instance=wiki_obj)
    return render(request, 'wiki_form.html', {'form': form})


# csrf_exempt装饰器免除csrf_token
# wiki_upload = csrf_exempt(wiki_upload)
@csrf_exempt
def wiki_upload(request, project_id):
    """ markdown插件上传图片 """

    result = {
        'success': 0,
        'message': None,
        'url': None,
    }

    image_obj = request.FILES.get('editormd-image-file')
    if not image_obj:
        result['message'] = '文件不存在'
        return JsonResponse(result)

    ext = image_obj.name.rsplit('.')[-1]
    key = '{}.{}'.format(uid(request.tracer.user.mobile_phone), ext)

    # 文件对象上传到当前项目的桶中
    image_url = upload_file(
        request.tracer.project.bucket,
        key,  # 上传到桶之后的文件名
        request.tracer.project.region,
        file_obj=image_obj,  # 文件对象
    )
    result['success'] = 1
    result['url'] = image_url
    return JsonResponse(result)
